<template>
  <a-modal
    width="700px"
    :footer="null"
    :maskClosable="false"
    :closable="false"
    :mask="false"
    v-model:open="modalShow"
    :wrap-style="{ overflow: 'hidden' }"
  >
    <template #title>
      <modalTitle @close="close" :title="'突发事件'"></modalTitle>
    </template>
    <div style="padding: 0 10px 10px 10px">
      <div class="content">
        <a-row :gutter="10">
          <a-col :span="13">
            <div class="leftBox">
              <div style="display: flex">
                <div style="flex: 1">
                  <div style="font-size: 12px; color: #ffffff99">报警时间</div>
                  <div style="font-size: 12px">{{ itemData.createtime }}</div>
                </div>
                <div style="flex: 1">
                  <div style="font-size: 12px; color: #ffffff99">报警地点</div>
                  <div class="ellipsis2" style="font-size: 12px">{{ itemData.event_address }}</div>
                </div>
              </div>
              <div style="margin-top: 10px">
                <div style="font-size: 12px; color: #ffffff99">报警内容</div>
                <div style="font-size: 12px">{{ itemData.content }}</div>
              </div>
              <div style="margin-top: 10px">
                <div style="font-size: 12px; color: #ffffff99">周边监控</div>
                <div
                  style="
                    border-radius: 5px;
                    margin-top: 5px;
                    background-image: url(&quot;/img/myimg/lk/jk1.png&quot;);
                    width: 100%;
                    height: 200px;
                    background-size: 100% 200px;
                  "
                ></div>
              </div>
              <div style="display: flex; align-items: center; justify-content: center; margin-top: 20px">
                <div class="btn" @click="btnclick(1)">现场处置人员</div>
                <div class="btn" @click="btnclick(2)">连麦现场</div>
                <div class="btn" @click="btnclick(3, itemData)">下发任务</div>
              </div>
            </div>
          </a-col>
          <a-col :span="11">
            <div class="rightBox">
              <div style="font-size: 14px; color: #d5f2ff">AI响应</div>
              <div
                style="
                  background-color: #d7d7d75c;
                  height: 322px;
                  border-radius: 5px;
                  margin: 5px 0;
                  padding: 10px;
                  overflow-y: auto;
                  scrollbar-width: none;
                  -ms-overflow-style: none;
                "
                ref="messageBox"
              >
                <div v-for="(item, index) in messageData" :key="index">
                  <!-- 发送 -->
                  <div style="display: flex; justify-content: flex-end; width: 100%" v-if="item.type == 'user'">
                    <div
                      style="width: 80%; padding: 5px; background-color: #ffffff; font-size: 10px; color: #000000; border-radius: 5px"
                      v-html="mdCtx.render(item.content)"
                    ></div>
                  </div>
                  <!-- AI回应 -->
                  <div style="display: flex; justify-content: flex-star; width: 100%" v-if="item.type == 'ai'">
                    <div
                      style="
                        width: 80%;
                        padding: 5px;
                        background-color: #43ecd8;
                        font-size: 10px;
                        margin-top: 10px;
                        color: #000000;
                        border-radius: 5px;
                      "
                      v-html="mdCtx.render(item.content)"
                    ></div>
                  </div>
                </div>
              </div>
              <div
                style="
                  display: flex;
                  align-items: center;
                  justify-content: space-between;
                  padding: 5px 10px;
                  background: #ffffff;
                  border-radius: 99px;
                "
              >
                <!-- <div style="color:#00000066; font-size: 12px; flex:1;">请输入</div> -->
                <input type="text" v-model="inputValue" style="color: #00000066; font-size: 12px; flex: 1" @keyup.enter="t_submit" class="input" />
                <!-- <div style="color:#ffffff; font-size: 10px; border-radius: 99px;background:#1C464B;padding:3px 10px;">发送语音</div> -->
                <div
                  style="color: #ffffff; margin-left: 5px; border-radius: 99px; font-size: 10px; background: #1c464b; padding: 3px 10px"
                  @click="t_submit"
                >
                  发送
                </div>
              </div>
            </div>
          </a-col>
        </a-row>
      </div>
    </div>
  </a-modal>
</template>
<script setup>
import { reactive, ref, nextTick } from "vue"
import { throttle } from "@mars/utils/throttle"
import MarkdownIt from "markdown-it"
import modalTitle from "../modalTitle.vue"
const emit = defineEmits(["btnclick"])
const btnclick = (e, item) => {
  emit("btnclick", { type: e, data: item })
}
const appKey = "app-DFxFJKprGTP8a7SdscJQpzLr"
const messageBox = ref(null)
const messageData = ref([])
const inputValue = ref("")
const isResponesEnd = ref(true)
const modalShow = ref(false)
const itemData = ref({})
let bufferObj
let txt
const resultObj = reactive({
  conversationId: "",
  taskId: "",
  messageId: ""
})
const messageObj = reactive({
  conversationId: "",
  taskId: "",
  messageId: ""
})
const mdCtx = new MarkdownIt({
  breaks: true,
  typographer: true,
  html: true
})
const close = () => {
  modalShow.value = false
}
const show = (e) => {
  console.log(e)
  modalShow.value = true
  console.log("modalShow:", modalShow.value)
  itemData.value = e
  inputValue.value = e.content
  t_submit()
  // setTimeout(() => {
  //   sendMessage(e.content)
  // }, 1000)
}
// 滚动到聊天框底部
const scrollToBottom = () => {
  if (messageBox.value) {
    messageBox.value.scrollTop = messageBox.value.scrollHeight
  }
}
const sendMessage = (inputValues) => {
  if (inputValues.trim() === "") {
    return // 防止空消息
  }
  messageData.value.push({ type: "user", content: inputValues }) // 添加新消息
  getResult(inputValues)
  inputValue.value = "" // 清空输入框
  // 等待 DOM 更新后滚动到底部
  nextTick(() => {
    scrollToBottom()
  })
}
async function getResult(query) {
  if (!isResponesEnd.value) {
    return
  }
  isResponesEnd.value = false
  const resp = await fetch("http://117.172.206.47:9346/v1/chat-messages", {
    method: "post",
    headers: {
      "Content-Type": "application/json;audio/wav",
      Authorization: `Bearer ${appKey}`
    },
    body: JSON.stringify({
      conversation_id: resultObj.conversationId,
      user: "abc-123",
      inputs: {
        group_name: "智慧园区智能体",
        company_name: "天一集团",
        yuanqu_name: "威斯腾物流园区"
      },
      query,
      response_mode: "streaming"
    })
  })
  // 获取流读取器
  const reader = resp?.body.getReader()
  // 字节数组转字符，创建文字解码器
  const decoder = new TextDecoder()

  // document.body.addEventListener("keydown", addStart)

  const str = ref("")
  console.log("str:", str)
  messageData.value.push({
    type: "ai",
    content: str
  })

  const unicodeToChar = async (text) => {
    str.value += text
    str.value = await mdCtx.render(str.value)
    console.log("str:", str.value)
    // messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
    // openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
    return text.replace(/\\u[0-9a-f]{4}/g, (_match, p1) => {
      return String.fromCharCode(parseInt(p1, 16))
    })
  }

  // 循环读取数据
  while (true) {
    const { done, value } = await reader.read()
    if (done) {
      return
    }

    // 解码
    txt += decoder.decode(value, { stream: true })
    const lines = txt.split("\n")

    try {
      lines.forEach((message) => {
        if (message.startsWith("data: ")) {
          try {
            bufferObj = JSON.parse(message.substring(6))
          } catch (e) {
            // mute handle message cut off
            // console.log(e)
            return
          }
          if (bufferObj.status === 400 || !bufferObj.event) {
            console.log("后端返回报错")
            return
          }
          if (bufferObj.event === "message" || bufferObj.event === "agent_message") {
            // can not use format here. Because message is splited.
            unicodeToChar(bufferObj.answer)
            resultObj.conversationId = bufferObj.conversation_id
            resultObj.taskId = bufferObj.task_id
            resultObj.messageId = bufferObj.id
          } else if (bufferObj.event === "agent_thought") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_file") {
            console.log(bufferObj)
          } else if (bufferObj.event === "message_end") {
            // setTimeout(() => {
            //   messageContentRef.value && (messageContentRef.value.scrollTop = messageContentRef.value?.scrollHeight)
            //   openRef.value && (openRef.value.scrollTop = openRef.value.scrollHeight)
            // })
            isResponesEnd.value = true
          } else if (bufferObj.event === "message_replace") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "workflow_finished") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_started") {
            console.log(bufferObj)
          } else if (bufferObj.event === "node_finished") {
            console.log(bufferObj)
          } else if (bufferObj.event === "tts_message") {
            // !show.value && audioPlayer.play(bufferObj.audio)
            messageObj.conversationId = bufferObj.conversation_id
            messageObj.taskId = bufferObj.task_id
            messageObj.messageId = bufferObj.id
          } else if (bufferObj.event === "tts_message_end") {
            // tts_message_end.value = true
          }
        }
      })
      txt = lines[lines.length - 1]
    } catch (e) {
      console.log(e)
      return
    }
  }
}
const t_submit = throttle(() => {
  sendMessage(inputValue.value)
})
defineExpose({ show, close })
</script>
<style scoped>
.content {
  /* background: #4DDECF1A; */
  /* padding: 10px 16px; */
  /* border: 1px solid #4DDECF33; */
  /* border-radius: 10px; */
  color: #ffffff;
  .leftBox {
    padding: 10px;
    background: #4ddecf1a;
    border-radius: 10px;
  }
  .rightBox {
    padding: 10px;
    background: #4ddecf1a;
    border-radius: 10px;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
  }
}
.btn {
  background: linear-gradient(180deg, rgba(0, 36, 42, 0.5) 0%, rgba(0, 67, 78, 0.5) 100%);
  border: 1px solid #57ffff;
  color: #ffffff;
  font-size: 10px;
  padding: 5px 20px;
  border-radius: 99px;
  cursor: pointer;
  margin-bottom: 0px;
  margin-left: 10px;
}

.ellipsis2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}
.input {
  all: unset;
}
</style>
